package com.niknik.woody.utils.wunit.junit.rule;

import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

import static java.text.MessageFormat.format;

public class TestInfoRule
    extends TestWatcher {

  private static final String TEST_CLASS_NAME_SUFF = "Test";
  private Description description;

  @Override
  protected void starting(Description description) {
    if (!description.getClassName().endsWith(TEST_CLASS_NAME_SUFF)) {
      throw new AssertionError("Test class name should ends with 'Test' word for using with WUnit");
    }

    this.description = description;
    super.starting(this.description);
  }

  public Class<?> getSubjectClass() {
    String testClassName = description.getClassName();
    String subjectClassName = testClassName.substring(0, testClassName.lastIndexOf(TEST_CLASS_NAME_SUFF));
    try {
      return Class.forName(subjectClassName);
    }
    catch (ClassNotFoundException e) {
      throw new AssertionError(format("Cannot find subject class {0} for test class {1}", subjectClassName,
          testClassName));
    }
  }
}